"""
MCP管理工具模块
提供LangChain工具来调用FastMCP管理服务
"""

import json
import asyncio
from typing import Dict, Any, Optional, List
from langchain.tools import BaseTool

from src.services.mcp_fastmanager import (
    register_server, unregister_server, list_servers, 
    get_server_info, check_health, discover_tools, invoke_tool
)


class MCPManagerTool(BaseTool):
    """MCP管理工具类，用于管理MCP服务器"""
    
    name: str = "mcp_manager"
    description: str = "管理MCP服务器，包括注册、注销、发现工具和调用工具等功能"
    
    def _run(self, action: str, **kwargs) -> str:
        """
        同步运行MCP管理工具
        
        Args:
            action: 要执行的操作
            **kwargs: 操作参数
            
        Returns:
            操作结果的JSON字符串
        """
        try:
            loop = asyncio.get_event_loop()
            
            if action == "register_server":
                result = loop.run_until_complete(
                    register_server(
                        name=kwargs.get("name"),
                        url=kwargs.get("url"),
                        description=kwargs.get("description"),
                        tags=kwargs.get("tags"),
                        api_key=kwargs.get("api_key")
                    )
                )
            elif action == "unregister_server":
                result = loop.run_until_complete(
                    unregister_server(server_id=kwargs.get("server_id"))
                )
            elif action == "list_servers":
                result = loop.run_until_complete(
                    list_servers(
                        status_filter=kwargs.get("status_filter"),
                        tag_filter=kwargs.get("tag_filter")
                    )
                )
            elif action == "get_server_info":
                result = loop.run_until_complete(
                    get_server_info(server_id=kwargs.get("server_id"))
                )
            elif action == "check_health":
                result = loop.run_until_complete(
                    check_health(server_id=kwargs.get("server_id"))
                )
            elif action == "discover_tools":
                result = loop.run_until_complete(
                    discover_tools(server_id=kwargs.get("server_id"))
                )
            elif action == "invoke_tool":
                result = loop.run_until_complete(
                    invoke_tool(
                        server_id=kwargs.get("server_id"),
                        tool_name=kwargs.get("tool_name"),
                        parameters=kwargs.get("parameters", {})
                    )
                )
            else:
                return f"未知操作: {action}"
                
            return json.dumps(result, ensure_ascii=False, indent=2)
        except Exception as e:
            return f"执行MCP管理操作失败: {str(e)}"
    
    async def _arun(self, action: str, **kwargs) -> str:
        """
        异步运行MCP管理工具
        
        Args:
            action: 要执行的操作
            **kwargs: 操作参数
            
        Returns:
            操作结果的JSON字符串
        """
        try:
            if action == "register_server":
                result = await register_server(
                    name=kwargs.get("name"),
                    url=kwargs.get("url"),
                    description=kwargs.get("description"),
                    tags=kwargs.get("tags"),
                    api_key=kwargs.get("api_key")
                )
            elif action == "unregister_server":
                result = await unregister_server(server_id=kwargs.get("server_id"))
            elif action == "list_servers":
                result = await list_servers(
                    status_filter=kwargs.get("status_filter"),
                    tag_filter=kwargs.get("tag_filter")
                )
            elif action == "get_server_info":
                result = await get_server_info(server_id=kwargs.get("server_id"))
            elif action == "check_health":
                result = await check_health(server_id=kwargs.get("server_id"))
            elif action == "discover_tools":
                result = await discover_tools(server_id=kwargs.get("server_id"))
            elif action == "invoke_tool":
                result = await invoke_tool(
                    server_id=kwargs.get("server_id"),
                    tool_name=kwargs.get("tool_name"),
                    parameters=kwargs.get("parameters", {})
                )
            else:
                return f"未知操作: {action}"
                
            return json.dumps(result, ensure_ascii=False, indent=2)
        except Exception as e:
            return f"执行MCP管理操作失败: {str(e)}"


def get_mcp_manager_tool() -> BaseTool:
    """
    获取MCP管理工具实例
    
    Returns:
        MCPManagerTool实例
    """
    return MCPManagerTool()


# 使用示例
if __name__ == "__main__":
    # 创建工具实例
    tool = get_mcp_manager_tool()
    
    # 示例：列出所有服务器
    result = tool._run("list_servers")
    print("列出服务器结果:")
    print(result)
    
    # 示例：检查所有服务器健康状态
    result = tool._run("check_health")
    print("\n健康检查结果:")
    print(result)